package cn.fzkj.utils;

import java.io.*;
import java.nio.file.Files;
import java.util.*;

/**
 * csv 导入导出工具类
 */
public class CSVUtil {

    // csv's default delemiter is ','
    private final static String DEFAULT_DELIMITER = ",";
    // Mark a new line
    private final static String DEFAULT_END = "\r\n";
    // If you do not want a UTF-8,just replace the byte array.
    private final static byte commonCsvHead[] = { (byte) 0xEF,(byte) 0xBB,(byte) 0xBF };

    /**
     * Write source to a csv file
     *
     * @param source
     * @throws IOException
     */
    public static void writeCsv(List<List<String>> source) throws IOException {
        // Aoid java.lang.NullPointerException
//        StringBuilder sbBuilder = new StringBuilder();
//        for (List<String> list : source) {
//            sbBuilder.append(Joiner.on(DEFAULT_DELIMITER).join(list)).append(
//                    DEFAULT_END);
//        }
//        Files.write(Bytes.concat(commonCsvHead,sbBuilder.toString().getBytes(Charsets.UTF_8.toString())),new File("d:\\/123.csv"));
    }




    /**
     * 导出
     *
     * @param file
     *            csv文件(路径+文件名)，csv文件不存在会自动创建
     * @param dataList
     *            数据
     * @return
     */
    public static boolean exportCsv(File file, List<Map<String, Object>> dataList) {
        boolean isSucess = false;

        FileOutputStream out = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        try {
            out = new FileOutputStream(file);
            osw = new OutputStreamWriter(out);
            bw = new BufferedWriter(osw);

            Set<String> titles = dataList.get(0).keySet();
            for (String title : titles) {
                bw.append(title).append(",");
            }
            bw.append("\r\n");
            if (dataList != null && !dataList.isEmpty()) {
                for (Map<String, Object> data : dataList) {
                    for (String title : titles) {
                        bw.append(String.valueOf(data.get(title))).append(",");
                    }
                    bw.append("\r\n");
                }
            }
            isSucess = true;
        } catch (Exception e) {
            e.printStackTrace();
            isSucess = false;
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                    bw = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (osw != null) {
                try {
                    osw.close();
                    osw = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                    out = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return isSucess;
    }


    public static void main(String[] args) {
        // https://www.cnblogs.com/hanfengyeqiao/p/9471694.html
        // https://blog.csdn.net/kpchen_0508/article/details/49755535
        File file = new File("/Users/yaya/test/test.csv");
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map;
        for (int i = 0; i < 10; i++) {
            map = new HashMap<String, Object>();
            map.put("name", "name" + i);
            map.put("address", "address" + i);
            list.add(map);
        }

        System.out.println(exportCsv(file, list));
    }


}


class User {
    public String name;
    public String add;
    public User(String name, String add){
        this.name = name;
        this.add = add;
    }
}
